import React, { useState, useEffect, useCallback, useRef } from 'react';
// import { Alert } from 'antd';
import request from '../request/request';
import useConnectSetting from '../context/useConnect';
import Table from './flexibleTable';
import Filter from './components/filter2';
import './index.less';
// import {} from '../../utils/date';
import EventsBus from '../utils/events';

const paginationConfig = {
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
  showSizeChanger: true,
  current: 1,
  pageSize: 20,
  total: 0,
  pageSizeOptions: ['5', '10', '20', '50', '100'],
};
export const tableScroll = (columns) => {
  if (!Array.isArray(columns)) {
    return;
  }
  return { x: 150 * columns.length };
};

const Index = (props) => {
  const filterRef = useRef(null);
  const setPagination = useRef(paginationConfig);
  const [loading, setLoading] = useState(true);
  const [dataSource, setDataSource] = useState([]);
  const [extra, setExtra] = useState({});
  const [queryOrderList, setQueryOrderList] = useState([]);
  const { current: pagination } = setPagination;
  const { mutilModel } = useConnectSetting(['mutilModel']); // 监听多标签属性的变化

  // 获取数据
  const getData = useCallback(
    async (params = {}) => {
      const localParams = { ...params };
      setLoading(true);
      const requestList = props.api
        ? [request(props.api, { data: localParams })]
        : [];
      if (props.count) {
        requestList.push(request(props.count, { data: localParams }));
      }
      Promise.all(requestList)
        .then((result) => {
          const queryExtra = {};
          if (result[0].models) {
            if (props.preResult) {
              const list =
                props.preResult(result[0].models, result[0].extra) || [];
              setDataSource(list || []);
            } else {
              setDataSource(result[0].models || []);
            }
          }
          if (result[0].extra) {
            queryExtra.extra = result[0].extra;
          }
          if (result[1]) {
            queryExtra.count = result[1].model || result[1].models;
          }
          if (result[0].pageInfo) {
            setPagination.current = {
              ...paginationConfig,
              pageSize: result[0].pageInfo.pageSize,
              current: result[0].pageInfo.pageIndex,
              total: result[0].pageInfo.total,
            };
          }
          if (queryExtra.count) {
            setExtra({ ...queryExtra });
          } else {
            setExtra({ ...queryExtra.extra });
          }
          setLoading(false);
        })
        .catch((e) => {
          setLoading(false);
        });
    },
    [props.api],
  );

  // 翻页
  const onPageChange = useCallback(
    (paginationParams, filters, sorter) => {
      const condition =
        filterRef.current && filterRef.current.getValues
          ? filterRef.current.getValues()
          : props.defaultCondition;

      const params = {
        condition,
        pagingQuery: {
          pageIndex: paginationParams.current,
          pageSize: paginationParams.pageSize,
        },
      };
      if (props.noPage) {
        delete params.pagingQuery;
      }
      if (sorter && sorter.order) {
        // 存在排序时
        params.queryOrderList = [
          {
            field: sorter.field,
            order: sorter.order === 'descend' ? 1 : 0,
          },
        ];
        setQueryOrderList(params.queryOrderList);
      } else {
        setQueryOrderList([]);
      }
      // todo 判断filters, 添加过滤条件
      getData({ ...params });
    },
    [pagination, props.defaultCondition, getData, filterRef],
  );
  const onSearch = useCallback(() => {
    onPageChange(
      { ...pagination, current: 1 },
      undefined,
      queryOrderList.length > 0 ? queryOrderList[0] : {},
    );
  }, [onPageChange]);

  // 页面初始化是
  // useEffect(() => {
  //   onSearch();
  // }, [props.defaultCondition]);

  // 多工作台，编辑页跳回首页，需要刷新列表页
  useEffect(() => {
    const { page } = props;
    if (!page) {
      return;
    }
    if (mutilModel) {
      window.filterTemporary && (window.filterTemporary = undefined);
      return;
    }
    window.filterTemporary = window.filterTemporary || {};
    const pageName = window.filterTemporary.name;
    if (pageName === page && filterRef.current) {
      if (filterRef.current.formRef && filterRef.current.formRef.current) {
        const formRefTemp = filterRef.current.formRef.current;

        formRefTemp.setFieldsValue({
          ...window.filterTemporary.value,
        });

        setPagination.current &&
          (setPagination.current.current = window.filterTemporary.pageIndex);
      }
    }
    return () => {
      if (!mutilModel && filterRef.current) {
        const pageName = page;
        const temporary =
          filterRef.current.getValues && filterRef.current.getValues();
        const index = setPagination.current && setPagination.current.current;
        window.filterTemporary = window.filterTemporary || {};
        window.filterTemporary.name = pageName;
        window.filterTemporary.value = temporary;
        window.filterTemporary.pageIndex = index;
      }
    };
  }, [mutilModel]);

  // 注册事件（多工作台，编辑页跳回首页，需要刷新列表页）
  useEffect(() => {
    const { page } = props;
    if (!page) {
      return;
    }
    window.reload = window.reload || {};
    if (!window.reload[page]) {
      window.reload[page] = function () {
        EventsBus.emit(page + '-reload');
      };
    }
    EventsBus.on(page + '-reload', () => {
      const { tableListRef } = props;
      if (tableListRef.current && tableListRef.current.reload) {
        tableListRef.current.reload();
      }
    });
    return () => {
      if (window.reload[page]) {
        window.reload[page] = undefined;
        EventsBus.removeListener(page + '-reload', () => {});
      }
    };
  }, []);

  // 放开对表格对控制
  useEffect(() => {
    const userAction = {
      reload: () => {
        onPageChange(
          pagination,
          undefined,
          queryOrderList.length > 0 ? queryOrderList[0] : {},
        );
      },
      reset: () => {},
      // clearSelected: () => {},
      getExtra: () => extra,
      getList: () => dataSource,
      filterRef: filterRef && filterRef.current,
    };
    const { tableListRef } = props;
    if (tableListRef && typeof tableListRef !== 'function') {
      tableListRef.current = userAction;
    }
  }, [pagination, queryOrderList, onPageChange, extra, dataSource]);
  return (
    <div
      className="xuanyue-Table"
      style={{ background: '#fff', padding: props.padding === 'none' ? 0 : 24 }}
    >
      {props.columnsFilter && (
        <Filter
          type={props.page}
          onSearch={onSearch}
          // onReset={()=>{}}
          columnsFilter={props.columnsFilter}
          defaultConditon={props.defaultCondition}
          ref={filterRef}
          submitPreMiddleware={props.submitPreMiddleware}
        />
      )}
      <Table
        loading={loading}
        page={props.page}
        tableHeader={props.tableHeader}
        size="middle"
        dataSource={dataSource}
        columns={props.columns}
        noPagination={props.noPagination}
        pagination={pagination}
        setPagination={setPagination}
        rowKey={props.rowKey || ((record) => `${record.id}`)}
        onChange={onPageChange}
        scroll={tableScroll(props.columns)}
        rowSelection={props.rowSelection}
        columnsFilter={props.columnsFilter}
      />
    </div>
  );
};

export default React.memo(Index);
